<!-- 商品资质 -->
<template>
  <div class="goodsCredential sys-content">
    <page-mod>
      <el-card>
        <div class="query-box">
          <el-form :model="query" inline>
            <el-form-item label="资质名称:">
              <el-input v-model="query.name" placeholder="请输入资质名称" clearable/>
            </el-form-item>
          </el-form>
          <div class="btns">
            <el-button icon="Search" color="#16b777" @click="load(1)">查询</el-button>
            <el-button icon="Plus" color="#FFB800" @click="show = true">新增</el-button>
            <el-button icon="Refresh" color="#FF5722" @click="resetSearch">重置</el-button>
          </div>
        </div>
      </el-card>
    </page-mod>
    <page-mod title="商品资质数据" icon="Tickets" :showBtn="false" :padBottom="false">
      <el-card v-loading="loading" element-loading-text="拼命加载中" >
        <el-row v-if="dataList.length" :gutter="16">
          <el-col v-for="item in dataList" :key="item.id" :span="3" style="margin-bottom: 15px;">
            <el-card shadow="hover" :body-style="{padding: '0px'}">
              <el-image :src="getImgSrc(item.attach)" :preview-src-list="getPics(item.attach)" :initial-index="0" fit="cover"/>
              <div class="info">
                <div class="name">{{ '资质名称：' + item.name }}</div>
                <div class="btn-box">
                  <el-button type="primary" link @click="toUpdate(item.credInfoId)">编辑</el-button>
                  <el-button type="danger" link @click="doDelete(item.credInfoId)">删除</el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
        <el-empty v-else description="暂无数据" />
        <el-pagination 
          class="paging"
          v-show="query.total"
          small
          layout="total, sizes, prev, pager, next, jumper" 
          :current-page="query.current" 
          :page-size="query.size"
          :total="query.total"
          @current-change="load"
          @size-change="sizeChange">
        </el-pagination>
      </el-card>
    </page-mod>

    <!-- 新增、编辑弹窗 -->
    <el-dialog v-model="show" :title="`${form.credInfoId ? '编辑' : '新增'}资质`" top="10vh" width="35%" destroy-on-close center draggable @close="resetForm">
      <el-form ref="formRef" :model="form" :rules="rules" size="default">
        <el-form-item label="资质名称" prop="name" required>
          <el-input v-model="form.name" placeholder="请输入资质名称" clearable/>
        </el-form-item>
        <el-form-item label="资质上传" prop="attach" required>
          <upload-img v-model="form.attach" multiple></upload-img>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" size="default" @click="doSubmit">保存</el-button>
        <el-button size="default" @click="show = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="goodsCredential">
  import { cudGoodsCredentialApi, getGoodsCredentialListPagesApi, getGoodsCredentialInfoApi } from '@/api/api'
  import { ref, reactive, toRefs, getCurrentInstance, onActivated } from 'vue'

  // 获取注册的全局实列
  const currentThis = getCurrentInstance().appContext.config.globalProperties
  
  const formRef = ref(null)

  const currentData = reactive({
    loading: false,
    show: false,
    query: {
      name: '',
      current: 1,
      size: 20,
      total: 0
    },
    dataList: [],
    form: {
      credInfoId: '',
      name: '',
      attach: ''
    },
    rules: {
      name: [{ required: true, message: '请输入资质名称', trigger: ['blur', 'change'] }],
      attach: [{ required: true, message: '请上传商品资质', trigger: ['blur', 'change'] }]
    }
  })
  let {loading, show, query, dataList, form, rules} = toRefs(currentData)

  // 查询
  function load(page) {
    currentData.loading = true
    currentData.query.current = page
    getGoodsCredentialListPagesApi(currentData.query).then(res => {
      currentData.loading = false
      if(res.code === '200') {
        currentData.dataList = res.data.pages
        currentData.query.total = res.data.total
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  // 新增或编辑
  function doSubmit() {
    formRef.value.validate((valid) => {
      if (valid) {
        currentThis.$messageBox.confirm(`确认${currentData.form.credInfoId ? '修改' : '新增'}吗？`).then(() => {
          let loading = currentThis.$loading(`正在${currentData.form.credInfoId ? '修改' : '新增'}`)
          cudGoodsCredentialApi(`${currentData.form.credInfoId ? 'update' : 'save'}`, currentData.form).then(res => {
            loading.close()
            if(res.code === '200') {
              currentThis.$message.success(res.message)
              currentData.show = false
              load(currentData.form.credInfoId ? currentData.query.current : 1)
            } else {
              currentThis.$message.error(res.message)
            }
          })
        }).catch(() => {})
      } else {
        return false;
      }
    })
  }

  // 删除
  function doDelete(credInfoId) {
    currentThis.$messageBox.confirm('确认删除吗？').then(() => {
      let loading = currentThis.$loading('正在删除，请耐心等待')
      cudGoodsCredentialApi('delete', { id: credInfoId }).then(res => {
        loading.close()
        if(res.code === '200') {
          currentThis.$message.success(res.message)
          load(currentData.query.current)
        } else {
          currentThis.$message.error(res.message)
        }
      })
    }).catch(() => {})
  }

  // 修改前获取详情并弹窗
  function toUpdate(credInfoId) {
    getGoodsCredentialInfoApi(credInfoId).then(res => {
      if(res.code === '200') {
        currentData.form.credInfoId = res.data.credInfoId
        currentData.form.name = res.data.name
        currentData.form.attach = res.data.attach
        currentData.show = true
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  // 获取资质图片字符串中的第一个图片地址
  function getImgSrc(e) {
    return e.substring(0, e.indexOf(','))
  }

  // 获取资质图片数组
  function getPics(e) {
    return e.split(',')
  }

  // 重置查询
  function resetSearch() {
    currentData.query.name = ''
    load(1)
  }

  function resetForm() {
    currentData.form = {
      credInfoId: '',
      name: '',
      attach: ''
    }
    formRef.value.resetFields()
  }

  function sizeChange(size) {
    currentData.query.size = size
    load(1)
  }

  onActivated(() => {
    load(currentData.query.current)
  })
</script>

<style lang="less" scoped>
.goodsCredential{
  :deep(.el-card){
    border-radius: 8px;
    .el-image{
      width: 100%;
      height: 180px;
    }
    .info{
      padding: 5px 6px 10px;
      .name{
        width: 100%;
        font-size: 12px;
        color: #7a7a7a;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
      .btn-box{
        display: flex;
        justify-content: flex-end;
        margin-top: 10px;
      }
    }
  }
  :deep(.el-dialog){
    .el-input, .el-textarea{
      width: 300px;
    }
  }
}
</style>